package com.fast.fast.upms.biz.base.face.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.fast.fast.upms.api.entity.SysDept;
import com.fast.fast.upms.api.vo.SysDeptVO;
import com.fast.fast.upms.biz.base.face.TreeConvert;
import com.fast.fast.upms.biz.base.face.enums.TreeEnum;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门树出参转换实现类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@Component
public class DeptTreeConvertImpl implements TreeConvert<List<SysDept>, List<SysDeptVO>> {

    /**
     * 部门树出参转换，需符合前端组件dtree的数据格式
     *
     * @param sysDepts 部门集合
     * @return
     */
    @Override
    public List<SysDeptVO> convert(List<SysDept> sysDepts) {
        List<SysDeptVO> sysDeptVos = sysDepts.stream().map(o -> {
            SysDeptVO sysDeptVO = BeanUtil.copyProperties(o, SysDeptVO.class, "children");
            sysDeptVO.setParentId(o.getPid());
            sysDeptVO.setTitle(o.getName());
            sysDeptVO.setSpread(true);
            JSONObject checkArr = new JSONObject();
            checkArr.put("checkArr", "{\"type\": \"0\", \"checked\": \"0\"}");
            sysDeptVO.setCheckArr(checkArr);
            if (o.getChildren() == null) {
                o.setChildren(new ArrayList<>());
            }
            sysDeptVO.setChildren(this.convert(o.getChildren()));
            return sysDeptVO;
        }).collect(Collectors.toList());
        return sysDeptVos;
    }

    /**
     * 部门树出参转换，需符合前端组件xmSelect的数据格式
     *
     * @param sysDepts 部门集合
     * @return
     */
    @Override
    public List<SysDeptVO> convert2(List<SysDept> sysDepts) {
        List<SysDeptVO> sysDeptVos = sysDepts.stream().map(o -> {
            SysDeptVO sysDeptVO = BeanUtil.copyProperties(o, SysDeptVO.class, "children");
            sysDeptVO.setValue(o.getId());
            if (o.getChildren() == null) {
                o.setChildren(new ArrayList<>());
            }
            sysDeptVO.setChildren(this.convert2(o.getChildren()));
            return sysDeptVO;
        }).collect(Collectors.toList());
        return sysDeptVos;
    }

    @Override
    public TreeEnum type() {
        return TreeEnum.DEPT_TREE;
    }
}
